package com.wvmi.gmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wvmi.gmall.cart.feign.ProductFeignService;
import com.wvmi.gmall.cart.interceptor.CartInterceptor;
import com.wvmi.gmall.cart.service.CartService;
import com.wvmi.gmall.cart.to.UserInfoTo;
import com.wvmi.gmall.cart.vo.CartItemVo;
import com.wvmi.gmall.cart.vo.CartVo;
import com.wvmi.gmall.cart.vo.SkuInfoVo;
import com.wvmi.gmall.common.constant.CartConstant;
import com.wvmi.gmall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 描述:   <br>
 *
 * @author Wuminming <br>
 * 创建时间: 2023-12-04 9:40 <br>
 * <p>
 * Copyright: 2013 - 2023 www.szwcyq.com Inc. All rights reserved. <br>
 * 注意：本内容仅限于深圳市微创云启科技有限公司内部传阅，禁止外泄以及用于其他的商业目的<br>
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException, IOException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String productRedisValue = (String) cartOps.get(skuId.toString());
        if (StringUtils.isBlank(productRedisValue)) {
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加商品的信息
                R info = productFeignService.getInfo(skuId);
                try {
                    SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                    cartItemVo.setSkuId(skuId);
                    cartItemVo.setTitle(skuInfo.getSkuTitle());
                    cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVo.setPrice(skuInfo.getPrice());
                    cartItemVo.setCount(num);
                } catch (IOException e) {
                }
            }, executor);

            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
                //2、远程查询skuAttrValues组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get();
            ObjectMapper objectMapper = new ObjectMapper();
            cartOps.put(skuId.toString(),objectMapper.writeValueAsString(cartItemVo));
            return cartItemVo;
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            CartItemVo cartItemVo = objectMapper.readValue(productRedisValue, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            cartOps.put(skuId.toString(),objectMapper.writeValueAsString(cartItemVo));
            return cartItemVo;
        }
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.THREAD_LOCAL.get();
        String cartKey = "";
        if (null != userInfoTo.getUserId()) {
            cartKey = CartConstant.CART_PREFIX +userInfoTo.getUserId();
        } else {
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
        }
        return stringRedisTemplate.boundHashOps(cartKey);
    }

    @Override
    public CartItemVo getCartItem(Long skuId) throws IOException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(res,new TypeReference<CartItemVo>(){});
    }

    @Override
    public CartVo getCart() throws IOException, ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.THREAD_LOCAL.get();
        CartVo cartVo = new CartVo();
        if (null != userInfoTo.getUserId()) {
            //临时购物车的键
            String temptCartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            //2、如果临时购物车的数据还未进行合并
            List<CartItemVo> tempCartItems = getCartItems(temptCartKey);
            if (tempCartItems != null) {
                //临时购物车有数据需要进行合并操作
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清除临时购物车的数据
                stringRedisTemplate.delete(temptCartKey);
            }
            cartVo.setItems(getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserId()));
        } else {
            cartVo.setItems(getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserKey()));
        }
        return cartVo;
    }

    /**
     * 获取购物车里面的数据
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey) {
        //获取购物车里面的所有商品
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        ObjectMapper objectMapper = new ObjectMapper();
        if(!CollectionUtils.isEmpty(values)){
            List<CartItemVo> itemVos = Objects.requireNonNull(hashOps.values()).stream().map(i -> {
                try {
                    return objectMapper.readValue((String) i,new TypeReference<CartItemVo>(){});
                } catch (IOException e) {
                    return new CartItemVo();
                }
            }).collect(Collectors.toList());
            return itemVos;
        }
        return null;
    }

    @Override
    public void deleteIdCartInfo(Integer skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) throws IOException, ExecutionException, InterruptedException {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        ObjectMapper objectMapper = new ObjectMapper();
        cartOps.put(skuId.toString(),objectMapper.writeValueAsString(cartItem));
    }

    @Override
    public void checkItem(Long skuId, Integer checked) throws IOException {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(checked != null && checked == 1);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        ObjectMapper objectMapper = new ObjectMapper();
        cartOps.put(skuId.toString(),objectMapper.writeValueAsString(cartItem));
    }

    @Override
    public List<CartItemVo> getUserCartItems() {

        List<CartItemVo> cartItemVoList = new ArrayList<>();
        //获取当前用户登录的信息
        UserInfoTo userInfoTo = CartInterceptor.THREAD_LOCAL.get();
        //如果用户未登录直接返回null
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            //获取购物车项
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            //获取所有的
            List<CartItemVo> cartItems = getCartItems(cartKey);
            if (cartItems == null) {
                throw new RuntimeException();
            }
            //筛选出选中的
            cartItemVoList = cartItems.stream()
                    .filter(CartItemVo::getCheck)
                    .peek(item -> {
                        //更新为最新的价格（查询数据库）
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                    })
                    .collect(Collectors.toList());
        }

        return cartItemVoList;
    }
}
